package com.mobartisan.workinglunch.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.codetroopers.betterpickers.calendardatepicker.CalendarDatePickerDialogFragment;
import com.codetroopers.betterpickers.radialtimepicker.RadialTimePickerDialogFragment;
import com.mobartisan.workinglunch.R;
import com.mobartisan.workinglunch.SnakeApplication;
import com.mobartisan.workinglunch.bean.AccountRecord;
import com.mobartisan.workinglunch.constants.Constants;
import com.mobartisan.workinglunch.ui.base.BaseActivity;
import com.mobartisan.workinglunch.ui.fragment.ListFragment;
import com.mobartisan.workinglunch.ui.fragment.PersonFragment;
import com.mobartisan.workinglunch.util.ObjectUtils;
import com.mobartisan.workinglunch.util.SharedPreferencesUtil;
import com.mobartisan.workinglunch.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import rx.Subscriber;

import static com.mobartisan.workinglunch.constants.Constants.FRAG_TAG_DATE_PICKER;
import static com.mobartisan.workinglunch.constants.Constants.FRAG_TAG_TIME_PICKER;

/**
 * Created by L on 2017/5/3.
 */

public class ChangeActivity extends BaseActivity implements CalendarDatePickerDialogFragment.OnDateSetListener, RadialTimePickerDialogFragment.OnTimeSetListener {

    private static final String TAG = ChangeActivity.class.getSimpleName();
    @Bind(R.id.rlt_date)
    RelativeLayout rlt_date;
    @Bind(R.id.rlt_time)
    RelativeLayout rlt_time;
    @Bind(R.id.rlt_type)
    RelativeLayout rlt_type;
    @Bind(R.id.tv_date)
    TextView tv_date;
    @Bind(R.id.tv_time)
    TextView tv_time;
    @Bind(R.id.tv_type)
    TextView tv_type;
    @Bind(R.id.buttonId)
    Button button;
    @Bind(R.id.et_money)
    EditText et_money;
    @Bind(R.id.common_title_left)
    ImageView imageView;
    String date, time, type, money, objectId;
    int typeInt;

    double moneynomber;
    boolean isexist = false;
    Map<String, Object> map = null;
    Handler handler = new Handler();
    int year1, monthOfYear1, dayOfMonth1, hourOfDay1, minute1;
    boolean isSame = false;
    public boolean isSuccess = false;
    int year2, monthOfYear2, dayOfMonth2;
    TextWatcher textWatcher;


    private TextView date2, time2, type2, money2, cancel, confirm, placeholder;
    private LinearLayout determine;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change);
        SnakeApplication.changeActivity = this;
        ButterKnife.bind(this);
        this.initView();
    }


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void initView() {
        TextView title = (TextView) findViewById(R.id.common_title_title);
        imageView.setVisibility(View.VISIBLE);
        title.setText("修改");
        button.setEnabled(false);
        button.setText("修改");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间  
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formatterdate1 = new SimpleDateFormat("yyyy");
        SimpleDateFormat formatterdate2 = new SimpleDateFormat("MM");
        SimpleDateFormat formatterdate3 = new SimpleDateFormat("dd");

        SimpleDateFormat formatter2 = new SimpleDateFormat("HH");
        SimpleDateFormat formatter3 = new SimpleDateFormat("mm");
        date = formatter1.format(curDate);
        time = formatter2.format(curDate) + ":" + formatter3.format(curDate);
        isSuccess = true;
        String hour = formatter2.format(curDate);
        String minutes = formatter3.format(curDate);
        String year = formatterdate1.format(curDate);
        String monthOfYear = formatterdate2.format(curDate);
        String dayOfMonth = formatterdate3.format(curDate);
        hourOfDay1 = Integer.valueOf(hour);
        minute1 = Integer.valueOf(minutes);
        year1 = Integer.valueOf(year);
        monthOfYear1 = Integer.valueOf(monthOfYear);
        dayOfMonth1 = Integer.valueOf(dayOfMonth);

        map = new HashMap<>();
        Bundle bundle = this.getIntent().getExtras();
        date = bundle.getString("dateStamp");
        map.put("dateStamp", date);
        time = bundle.getString("timeStamp");
        map.put("timeStamp", time);
        typeInt = bundle.getInt("type");
        map.put("type", typeInt);
        if (date.equals(joint2(year1, monthOfYear1 - 1, dayOfMonth1))) {
            isSame = true;
        }
        SharedPreferencesUtil.getInstance().setIntValue("type1", typeInt);
        switch (typeInt) {
            case 0:
                type = "早上";
                break;
            case 1:
                type = "中午";
                break;
            case 2:
                type = "晚上";
                break;
            case 3:
                type = "其它";
                break;
        }
        money = bundle.getString("money");
        map.put("money", money);
        objectId = bundle.getString("objectId");
        map.put("objectId", objectId);
        tv_date.setText(date);
        tv_time.setText(time);
        tv_type.setText(type);
        et_money.setText(money);
        et_money.setSelection(et_money.getText().length());
        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.e(TAG, "beforeTextChanged: =======================");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e(TAG, "onTextChanged: =======================");
                buttonChange();
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e(TAG, "afterTextChanged: =======================");
            }

        };
        et_money.addTextChangedListener(textWatcher);
    }

    @OnClick({R.id.rlt_date, R.id.rlt_time, R.id.rlt_type, R.id.buttonId, R.id.common_title_left})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.common_title_left:
                finish();
                break;
            case R.id.rlt_date:
                CalendarDatePickerDialogFragment cdp = new CalendarDatePickerDialogFragment()
                        .setOnDateSetListener(this);
                cdp.show(getSupportFragmentManager(), FRAG_TAG_DATE_PICKER);
                break;
            case R.id.rlt_time:
                RadialTimePickerDialogFragment rtpd = new RadialTimePickerDialogFragment()
                        .setOnTimeSetListener(this);
                rtpd.show(getSupportFragmentManager(), FRAG_TAG_TIME_PICKER);
                break;
            case R.id.rlt_type:
                showDilog(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.rlt_morning:
                                type = breakfast.getText().toString();
                                tv_type.setText(type);
                                ismorning.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type1", 0);
                                buttonChange();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                            case R.id.rlt_nooning:
                                type = lunch.getText().toString();
                                tv_type.setText(type);
                                isnooning.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type1", 1);
                                buttonChange();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                            case R.id.rlt_night:
                                type = dinner.getText().toString();
                                tv_type.setText(type);
                                isnight.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type1", 2);
                                buttonChange();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                            case R.id.rlt_other:
                                type = other.getText().toString();
                                tv_type.setText(type);
                                isother.setVisibility(View.VISIBLE);
                                SharedPreferencesUtil.getInstance().setIntValue("type1", 3);
                                buttonChange();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        dismissDilog();
                                    }
                                }, 100);
                                break;
                        }
                    }
                });
                break;
            case R.id.buttonId:
                money = et_money.getText().toString();
                if (!ObjectUtils.isStringNotEmpty(money)) {
                    ToastUtils.showShort("请输入金额");
                    return;
                }
                moneynomber = Double.parseDouble(money);
                if (!ObjectUtils.isStringNotEmpty(date) || !ObjectUtils.isStringNotEmpty(time) || !ObjectUtils.isStringNotEmpty(type) || !ObjectUtils.isStringNotEmpty(money)) {
                    ToastUtils.showShort("请正确填入信息");
                } else {
                    if (moneynomber > 1000) {
                        ToastUtils.showShort("输入金额不可超过1000，请重新输入");
                        et_money.setText("");
                    } else if (moneynomber <= 0) {
                        ToastUtils.showShort("输入金额需要大于0，请重新输入");
                        et_money.setText("");
                    } else {

                        typeInt = SharedPreferencesUtil.getInstance().getIntValue("type1");
                        if ((map.get("dateStamp").equals(date)) && (map.get("type") == Integer.valueOf(typeInt))) {
                            amendObject();
                        } else {
                            queryObjects();
                        }


                    }
                }
                break;
        }
    }

    private void amendObject() {

        AccountRecord accountRecord = new AccountRecord();
        accountRecord.setValue("dateStamp", date);
        accountRecord.setValue("timeStamp", time);
        accountRecord.setValue("type", typeInt);
        accountRecord.setValue("money", moneynomber);
        accountRecord.update(objectId, new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.i("bmob", "更新成功");
                    ListFragment.getFragmetntA().handler.sendEmptyMessage(0);
                    PersonFragment.getFragmetntA().handler.sendEmptyMessage(0);
                    isSame = false;
                    isSuccess = false;
                    finish();
                } else {

                    Log.i("bmob", "更新失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {


        if (year1 > year) {
            isSame = false;
            showdate(year, monthOfYear, dayOfMonth);
        } else if (year1 == year) {
            if (monthOfYear1 > (monthOfYear + 1)) {
                isSame = false;
                showdate(year, monthOfYear, dayOfMonth);
            } else if (monthOfYear1 == (monthOfYear + 1)) {
                if (dayOfMonth1 > dayOfMonth) {
                    isSame = false;
                    showdate(year, monthOfYear, dayOfMonth);
                } else if (dayOfMonth1 == dayOfMonth) {
                    if (!isSuccess) {
                        ToastUtils.showShort("不可输入未来时间");
                    } else {
                        isSame = true;
                        showdate(year, monthOfYear, dayOfMonth);
                    }
                } else {
                    ToastUtils.showShort("不可输入未来时间");
                }
            } else {
                ToastUtils.showShort("不可输入未来时间");
            }
        } else {
            ToastUtils.showShort("不可输入未来时间");
        }
    }

    private void showdate(int year, int monthOfYear, int dayOfMonth) {
        joint(year, monthOfYear, dayOfMonth);
        tv_date.setText(date);

    }

    private String joint(int year, int monthOfYear, int dayOfMonth) {
        String month = "" + (monthOfYear + 1), day = "" + dayOfMonth;

        if (monthOfYear < 10) {
            month = "0" + (monthOfYear + 1);
        }
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        }
        date = year + "-" + month + "-" + day;
        buttonChange();
        return date;
    }

    @Override
    public void onTimeSet(RadialTimePickerDialogFragment dialog, int hourOfDay, int minute) {
        if (!isSame) {
            if (hourOfDay1 < hourOfDay) {
                isSuccess = false;
            } else if (hourOfDay1 == hourOfDay && minute1 < (minute - 5)) {
                isSuccess = false;
            } else if (hourOfDay1 == hourOfDay && minute1 >= (minute - 5)) {
                isSuccess = true;
            } else if (hourOfDay1 > hourOfDay) {
                isSuccess = true;
            }
            showtime(hourOfDay, minute);
        } else {
            if (hourOfDay1 > hourOfDay) {
                isSuccess = true;
                showtime(hourOfDay, minute);
            } else if (hourOfDay1 == hourOfDay) {
                if (minute1 >= (minute - 5)) {
                    isSuccess = true;
                    showtime(hourOfDay, minute);
                } else {
                    ToastUtils.showShort("不可输入未来时间");
                }

            } else {
                ToastUtils.showShort("不可输入未来时间");
            }
        }
    }

    private void showtime(int hourOfDay, int minute) {

        if (minute < 10 && hourOfDay < 10) {
            time = "0" + hourOfDay + ":0" + minute;
        } else if (hourOfDay >= 10 && minute < 10) {
            time = hourOfDay + ":0" + minute;
        } else if (hourOfDay < 10 && minute >= 10) {
            time = "0" + hourOfDay + ":" + minute;
        } else {
            time = hourOfDay + ":" + minute;
        }
        tv_time.setText(time);
        if ((5 <= hourOfDay && hourOfDay < 9) || (hourOfDay == 9 && minute <= 30)) {
            type = "早上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type1", 0);
        } else if ((11 <= hourOfDay && hourOfDay < 14) || (hourOfDay == 14 && minute == 0)) {
            type = "中午";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type1", 1);
        } else if (17 <= hourOfDay && hourOfDay < 20 || (hourOfDay == 20 && minute <= 30)) {
            type = "晚上";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type1", 2);
        } else {
            type = "其它";
            tv_type.setText(type);
            SharedPreferencesUtil.getInstance().setIntValue("type1", 3);
        }
        buttonChange();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    public void queryObjects() {
        String userId = SharedPreferencesUtil.getInstance().getStringValue("username");
        final BmobQuery<AccountRecord> bmobQuery = new BmobQuery<AccountRecord>();
        bmobQuery.addWhereEqualTo("userId", userId);
        bmobQuery.addWhereEqualTo("dateStamp", date);

        //bmobQuery.setLimit(2);
//        bmobQuery.order("createdAt");
//        //先判断是否有缓存
//        boolean isCache = bmobQuery.hasCachedResult(AccountRecord.class);
//        if(isCache){
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK);	// 先从缓存取数据，如果没有的话，再从网络取。
//        }else{
//            bmobQuery.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);	// 如果没有缓存的话，则先从网络中取
//        }
//		observable形式
        bmobQuery.findObjectsObservable(AccountRecord.class)
                .subscribe(new Subscriber<List<AccountRecord>>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (((BmobException) e).getErrorCode() == Constants.Network_Error_Code) {
                            ToastUtils.showShort("更新失败,请检查您的网络");
                        } else if (((BmobException) e).getErrorCode() == Constants.Network_Timeout_Code) {
                            ToastUtils.showShort("网络超时");
                        }
                        loge(e, TAG);
                    }

                    @Override
                    public void onNext(List<AccountRecord> persons) {
                        //log("查询成功：共"+persons.size()+"条数据。");
                        //ToastUtils.showShort("查询成功：共" + persons.size() + "条数据。");
                        for (AccountRecord accountRecord : persons) {
                            if (accountRecord.getType() == typeInt) {
                                isexist = true;
                            }
                        }
                        if (isexist) {
                            ToastUtils.showShort("此类型的记录已经存在");
                            isexist = false;
                        } else {
                            amendObject();
                        }

                    }
                });
//		bmobQuery.findObjects(new FindListener<Person>() {
//
//			@Override
//			public void done(List<Person> object, BmobException e) {
//				if(e==null){
//					toast("查询成功：共"+object.size()+"条数据。");
//					for (Person person : object) {
//						Log.d(TAG, "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ");
//						Log.d(TAG, "ObjectId = "+person.getObjectId());
//						Log.d(TAG, "Name = "+person.getName());
//						Log.d(TAG, "Age = "+person.getAge());
//						Log.d(TAG, "Address = "+person.getAddress());
//						Log.d(TAG, "Gender = "+person.isGender());
//						Log.d(TAG, "CreatedAt = "+person.getCreatedAt());
//						Log.d(TAG, "UpdatedAt = "+person.getUpdatedAt());
//					}
//				}else{
//					loge(e);
//				}
//			}
//		});
    }

    private String joint2(int year, int monthOfYear, int dayOfMonth) {
        String month = "" + (monthOfYear + 1), day = "" + dayOfMonth;
        String testdate;
        if (monthOfYear < 10) {
            month = "0" + (monthOfYear + 1);
        }
        if (dayOfMonth < 10) {
            day = "0" + dayOfMonth;
        }
        testdate = year + "-" + month + "-" + day;
        return testdate;
    }

    private void buttonChange() {
        double money1 = Double.parseDouble((String) map.get("money"));
        double money2 = 0;
        if (!et_money.getText().toString().equals(""))
            money2 = Double.parseDouble(et_money.getText().toString());
        if ((map.get("timeStamp").equals(time)) && (map.get("dateStamp").equals(date)) && (map.get("type").equals(SharedPreferencesUtil.getInstance().getIntValue("type1"))) && (money1 == money2)) {
            button.setEnabled(false);
        } else {
            button.setEnabled(true);
        }
    }
}
